package com.example.aigc_education.security.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.aigc_education.common.BusinessException;
import com.example.aigc_education.domain.User;
import com.example.aigc_education.mapper.MenuMapper;
import com.example.aigc_education.mapper.UserMapper;
import com.example.aigc_education.security.domain.LoginUser;
import com.example.aigc_education.utils.SecurityUtils;
import com.example.aigc_education.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 用户加载校验
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private MenuMapper menuMapper;

    /**
     * 查询用户信息
     * @param username 用户名
     * @return 用户信息
     * @throws UsernameNotFoundException 用户名未找到异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, username);
        User user = userMapper.selectOne(wrapper);
        // 判断用户是否存在
        if(Objects.isNull(user)){
            throw new BusinessException("账号错误");
        }
        // 校验用户密码
        validate(user);
        // 查询用户权限
        List<String> permsList = menuMapper.selectPermsByUserId(user.getUserId());
        log.info("用户编号{}权限:{}", user.getUserId(), permsList);
        // 返回用户信息
        return new LoginUser(user, permsList);
    }

    /**
     * 校验用户密码
     * @param user 用户信息
     */
    private void validate(User user){
        // ThreadLocal获取用户信息上下文
        Authentication AuthenticationToken = ThreadLocalUtil.getContext();
//        String phone = phonePasswordAuthenticationToken.getName();
        String password = AuthenticationToken.getCredentials().toString();

        // 判断输入的用户密码与数据库的密码是否一致
        if (!matches(user, password)){
            throw new BusinessException("密码错误");
        }

    }


    private boolean matches(User user, String rawPassword){
        return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
    }
}
